#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <set>

const int line_size = 1024;

class Command
{
public:
    //给你一个命令字符串"ls -l", 让你执行, 执行完, 把结果返回
    std::string Execute(std::string cmdstr)
    {
        //1.pipe
        //2.fork + dup2(pipe[1], 1) + exec*, 执行结果给父进程, pipe[0]
        //3.return
        //popen一下子就可以干完这三件事情
        //FILE *popen(const char *command, const char *type);
        //int pclose(FILE * stream);
        FILE *fp = ::popen(cmdstr.c_str(), "r"); //读取干完的命令结果
        if(nullptr == fp)
        {
            return std::string("Failed");
        }
        char buffer[line_size];
        std::string result;
        while(true)
        {
            char *ret = ::fgets(buffer, sizeof(buffer), fp);
            if(!ret)
                break;
            result += ret;
        }
        pclose(fp);
        return result.empty() ? std::string("Done") : result;
    }

};